package com.wrl.mmall.controller.backend;

import com.wrl.mmall.common.Const;
import com.wrl.mmall.common.ServerResponse;
import com.wrl.mmall.pojo.User;
import com.wrl.mmall.service.IUserService;
import com.wrl.mmall.util.CookieUtil;
import com.wrl.mmall.util.JsonUtil;
import com.wrl.mmall.util.RedisShardedPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 管理员登陆
 * Created by Wang Renlei on 2018/8/22.
 */
@Slf4j
@Controller
@RequestMapping("/manage/user")
public class UserManageController {

    @Autowired
    private IUserService iUserService;

    /**
     * 管理员登录
     *
     * @param httpServletResponse
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "login.do")
    @ResponseBody
    public ServerResponse<User> login(HttpServletResponse httpServletResponse, HttpSession session, String username, String password) {
        log.info("UserManageController.login");
        ServerResponse<User> response = iUserService.login(username, password);
        if (response.isSuccess()) {
            //请求成功
            User user = response.getData();
            if (user.getRole() == Const.Role.ROLE_ADMIN) {
                //说明登陆的是管理员
                CookieUtil.writeLoginToken(httpServletResponse, session.getId());
                RedisShardedPoolUtil.setEx(session.getId(),JsonUtil.objToString(response.getData()),Const.RedisCacheExtime.REDIS_SESSION_EXTIME);
                return response;
            } else {
                return ServerResponse.createByErrorMessage("不是管理员，无法登陆");
            }
        }
        return response;
    }
}
